package cn.fzhui.servlet;

import cn.fzhui.factory.ServiceFactory;
import cn.fzhui.model.Student;
import cn.fzhui.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class EditStudentServlet extends AuthServlet {

    /**
     * 编辑页面
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StudentService studentService = ServiceFactory.getStudentService();
        try {
            req.setAttribute("student", studentService.findById(Integer.parseInt(req.getParameter("id"))));
            req.getRequestDispatcher("/edit.jsp").forward(req, resp);
        } catch (SQLException exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 更新数据
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        StudentService studentService = ServiceFactory.getStudentService();
        try {
            Student student = studentService.findById(Integer.parseInt(req.getParameter("id")));
            if (student == null) {
                // 数据不存在
                return;
            }

            student.setNumber(req.getParameter("number"));
            student.setName(req.getParameter("name"));
            student.setSex(req.getParameter("sex"));
            student.setBirthday(req.getParameter("birthday"));
            student.setEmail(req.getParameter("email"));
            student.setRemark(req.getParameter("remark"));
            student.setPassword(req.getParameter("password"));
            student.setAge(Integer.parseInt(req.getParameter("age")));

            studentService.update(student);
        } catch (SQLException exception) {
            exception.printStackTrace();
        }
        resp.sendRedirect("/index");
    }
}
